/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
"use strict";
// $LayaFlag
(function() {
	function getConfig() {
		let queryParams = window.location.search.substring(1).split('&');
		for (let i = 0; i < queryParams.length; i++) {
			var kv = queryParams[i].split('=');
			if (kv[0] === 'config' && kv[1]) {
				return JSON.parse(decodeURIComponent(kv[1]));
			}
		}
		return {};
	}
	try {
		let config = getConfig();
		let document = window.document;

		// sets the base theme class ('vs', 'vs-dark', 'hc-black')
		let baseTheme = config.baseTheme || 'vs';
		document.body.className = 'monaco-shell ' + baseTheme;

		// adds a stylesheet with the backgrdound color
		let backgroundColor = config.backgroundColor;
		if (!backgroundColor) {
			backgroundColor = baseTheme === 'hc-black' ? '#000000' : (baseTheme === 'vs' ? '#FFFFFF' : '#1E1E1E');
		}
		let style = document.createElement('style');
		style.innerHTML = '.monaco-shell { background-color:' + backgroundColor + '; }';
		document.head.appendChild(style);

	} catch (error) {
		console.error(error);
	}
})();


// VSCode start
function onError(e, n) {
    n && remote.getCurrentWebContents().openDevTools(),
    console.error("[uncaught exception]: " + e),
    e.stack && console.error(e.stack)
}
function assign(e, n) {
    return Object.keys(n).reduce(function(e, r) {
        return e[r] = n[r],
        e
    }, e)
}
function parseURLQueryArgs() {
    return (window.location.search || "").split(/[?&]/).filter(function(e) {
        return !!e
    }).map(function(e) {
        return e.split("=")
    }).filter(function(e) {
        return 2 === e.length
    }).reduce(function(e, n) {
        return e[n[0]] = decodeURIComponent(n[1]),
        e
    }, {})
}
// $LayaFlag
function createScript(e, r) {
	const n = document.createElement("script");
	n.src = e, n.addEventListener("load", r);
	const t = document.getElementsByTagName("head")[0];
	t.insertBefore(n, t.lastChild)
}
function uriFromPath(e) {
    var n = path.resolve(e).replace(/\\/g, "/");
    return n.length > 0 && "/" !== n.charAt(0) && (n = "/" + n),
    encodeURI("file://" + n)
}
function readFile(e) {
    return new Promise(function(n, r) {
        fs.readFile(e, "utf8", function(e, t) {
            e ? r(e) : n(t)
        })
    }
    )
}
function registerListeners(e) {
    var n;
    if (e) {
        const e = "darwin" === process.platform ? "meta-alt-73" : "ctrl-shift-73"
          , r = "darwin" === process.platform ? "meta-82" : "ctrl-82";
        n = function(n) {
            const t = function(e) {
                return [e.ctrlKey ? "ctrl-" : "", e.metaKey ? "meta-" : "", e.altKey ? "alt-" : "", e.shiftKey ? "shift-" : "", e.keyCode].join("")
            }(n);
            t === e ? remote.getCurrentWebContents().toggleDevTools() : t === r && remote.getCurrentWindow().reload()
        }
        ,
        window.addEventListener("keydown", n)
    }
    return process.on("uncaughtException", function(n) {
        onError(n, e)
    }),
    function() {
        n && (window.removeEventListener("keydown", n),
        n = void 0)
    }
}
function main() {
    const e = require("electron").webFrame
      , n = parseURLQueryArgs()
      , r = JSON.parse(n.config || "{}") || {};
    !function() {
        const e = require("path")
          , n = require("module");
        let t = e.join(r.appRoot, "node_modules");
        /[a-z]\:/.test(t) && (t = t.charAt(0).toUpperCase() + t.substr(1));
        const o = t + ".asar"
          , i = n._resolveLookupPaths;
        n._resolveLookupPaths = function(e, n) {
            const r = i(e, n)
              , s = r[1];
            for (let e = 0, n = s.length; e < n; e++)
                if (s[e] === t) {
                    s.splice(e, 0, o);
                    break
                }
            return r
        }
    }(),
    assign(process.env, r.userEnv),
    perf.importEntries(r.perfEntries);
    var t = {
        availableLanguages: {}
    };
    const o = process.env.VSCODE_NLS_CONFIG;
    if (o) {
        process.env.VSCODE_NLS_CONFIG = o;
        try {
            t = JSON.parse(o)
        } catch (e) {}
    }
    if (t._resolvedLanguagePackCoreLocation) {
        let e = Object.create(null);
        t.loadBundle = function(n, r, o) {
            let i = e[n];
            if (i)
                return void o(void 0, i);
            readFile(path.join(t._resolvedLanguagePackCoreLocation, n.replace(/\//g, "!") + ".nls.json")).then(function(r) {
                let t = JSON.parse(r);
                e[n] = t,
                o(void 0, t)
            }).catch(o)
        }
    }
	var i = t.availableLanguages["*"] || "en";
	// $LayaFlag
	window.laya_available_languages = i;

    "zh-tw" === i ? i = "zh-Hant" : "zh-cn" === i && (i = "zh-Hans"),
    window.document.documentElement.setAttribute("lang", i);
    const s = (process.env.VSCODE_DEV || !!r.extensionDevelopmentPath) && !r.extensionTestsPath
      , a = registerListeners(s)
      , c = r.zoomLevel;
    e.setVisualZoomLevelLimits(1, 1),
    "number" == typeof c && 0 !== c && e.setZoomLevel(c);
    const l = r.appRoot + "/out/vs/loader.js"
      , u = require("fs").readFileSync(l);
	// $LayaFlag
    // require("vm").runInThisContext(u, {
    //     filename: l
    // });
	// $LayaFlag
    createScript(l, function() {
        var d = global.define;
        global.define = void 0,
        window.nodeRequire = require.__$__nodeRequire,
        d("fs", ["original-fs"], function(e) {
            return e
        }),
        window.MonacoEnvironment = {};
        const p = window.MonacoEnvironment.onNodeCachedData = [];
        require.config({
            baseUrl: uriFromPath(r.appRoot) + "/out",
            "vs/nls": t,
            recordStats: !!r.performance,
            nodeCachedDataDir: r.nodeCachedDataDir,
            onNodeCachedData: function() {
                p.push(arguments)
            },
            nodeModules: ["electron", "original-fs", "vsda", "nan", "applicationinsights", "fast-plist", "gc-signals", "getmac", "graceful-fs", "http-proxy-agent", "https-proxy-agent", "iconv-lite", "jschardet", "keytar", "minimist", "native-is-elevated", "native-keymap", "native-watchdog", "node-pty", "nsfw", "semver", "spdlog", "sudo-prompt", "v8-inspect-profiler", "vscode-chokidar", "vscode-fsevents", "vscode-debugprotocol", "vscode-ripgrep", "vscode-textmate", "vscode-xterm", "vsda", "yauzl", "windows-foreground-love", "windows-mutex", "windows-process-tree", "agent-base", "anymatch", "async-each", "bindings", "buffer-crc32", "chrome-remote-interface", "debug", "ms", "extend", "extract-opts", "fd-slicer", "fs-extra", "glob-parent", "inherits", "is-binary-path", "is-glob", "lodash.isinteger", "lodash.isundefined", "mkdirp", "oniguruma", "path-is-absolute", "promisify-node", "readdirp", "binary-extensions", "commander", "is-extglob", "jsonfile", "klaw", "micromatch", "normalize-path", "minimatch", "nodegit-promise", "pend", "readable-stream", "rimraf", "set-immediate-shim", "typechecker", "ws", "arr-diff", "array-unique", "asap", "async-limiter", "brace-expansion", "concat-map", "braces", "core-util-is", "expand-brackets", "extglob", "filename-regex", "glob", "isarray", "kind-of", "object.omit", "parse-glob", "process-nextick-args", "regex-cache", "remove-trailing-separator", "safe-buffer", "string_decoder", "ultron", "util-deprecate", "arr-flatten", "balanced-match", "expand-range", "for-own", "fs.realpath", "glob-base", "inflight", "is-buffer", "is-dotfile", "is-equal-shallow", "is-extendable", "is-posix-bracket", "is-primitive", "once", "preserve", "repeat-element", "fill-range", "for-in", "wrappy", "is-number", "isobject", "randomatic", "repeat-string", "async_hooks", "assert", "buffer", "child_process", "console", "constants", "crypto", "cluster", "dgram", "dns", "domain", "events", "fs", "http", "http2", "https", "inspector", "module", "net", "os", "path", "perf_hooks", "process", "punycode", "querystring", "readline", "repl", "stream", "string_decoder", "sys", "timers", "tls", "tty", "url", "util", "v8", "vm", "zlib"]
        }),
        t.pseudo && require(["vs/nls"], function(e) {
            e.setPseudoTranslation(t.pseudo)
        }),
        window.MonacoEnvironment.timers = {
            isInitialStartup: !!r.isInitialStartup,
            hasAccessibilitySupport: !!r.accessibilitySupport,
            start: r.perfStartTime,
            windowLoad: r.perfWindowLoadTime
        },
        perf.mark("willLoadWorkbenchMain"),
        require(["vs/workbench/workbench.main", "vs/nls!vs/workbench/workbench.main", "vs/css!vs/workbench/workbench.main"], function() {
            perf.mark("didLoadWorkbenchMain"),
            process.lazyEnv.then(function() {
                perf.mark("main/startup"),
                require("vs/workbench/electron-browser/main").startup(r).done(function() {
                    a()
                }, function(e) {
                    onError(e, s)
                })
            })
        })
    })
}
const perf = require("../../base/common/performance");
perf.mark("renderer/started");
var path = require("path")
  , fs = require("fs")
  , electron = require("electron")
  , remote = electron.remote
  , ipc = electron.ipcRenderer;
process.lazyEnv = new Promise(function(e) {
    const n = setTimeout(function() {
        e(),
        console.warn("renderer did not receive lazyEnv in time")
    }, 1e4);
    ipc.once("vscode:acceptShellEnv", function(r, t) {
        clearTimeout(n),
        assign(process.env, t),
        e(process.env)
    }),
    ipc.send("vscode:fetchShellEnv", remote.getCurrentWindow().id)
}
); //,
// main();
// VSCode end
// $LayaFlag

ipc.send("close.launch.page");

// remote.getCurrentWebContents().openDevTools()
////////

var langindex = 1;
var ctrlreplacecmd;
var shiftreplacecmd;
if (process.platform == "win32") {
	ctrlreplacecmd = "Ctrl";
	shiftreplacecmd = "Shift";
} else {
	ctrlreplacecmd = "⌘";
	shiftreplacecmd = "⇧"
}
// var electron = require('electron');
// var remote = electron.remote;
// var ipc = electron.ipcRenderer;
var childProcess = require("child_process");
// var layaunzip = require("unzip");
// var layarequest = require('request');
var _chokidar =require("chokidar");
////改造vscode入口类
// var fs = require("fs");
// var path = require("path")

var CodeMains = require("./codemain.js");
var codeMain = new CodeMains();
codeMain.initDa();

var _bar = codeMain.require("./../../../layarepublic/toolbar/extension.js");
new _bar.__LayaToolBar();
setTimeout(function() {
	var _pathextension = path.join(__dirname, './../../../codeextension');
	var union = fs.readdirSync(_pathextension);
	var stat = fs.statSync;
	for (var i = 0; i < union.length; i++) {
		var itemdir = path.join(_pathextension, union[i]);
		if (stat(itemdir).isDirectory()) {
			if (path.join(itemdir, "extension.js")) {
                try {
                    var mode = codeMain.require(path.join(itemdir, "extension.js"));
                    mode.activate();
                } catch(e) {
                    console.error('不符合扩展规则: ', e);
                }
			}
		}
	}
}, 1000)


function buldAppSdk() {
	localStorage.setItem("layapublishworkspace", path.join(codeMain.workspacePath, "release", "app", "config"));
	codeMain.once('publishProComplete', function() {
		codeMain.mkdirsSync(path.join(codeMain.workspacePath, "release", "app", "config")); //创建文件夹；
		var window = new remote.BrowserWindow({
			width: 800,
			height: 604,
			show: false,
			center: true,
			frame: false,
			resizable: false
		});
		window.loadURL("file:///" + path.join(__dirname, './../../../layarepublic/sdks/index.html'));
		//window.openDevTools();
		setTimeout(function() {
			window.show()
		}, 1000)
	})
	// new codeMain.layapublishwebversion.LayaPublishPro();
	codeMain.emit("publishProComplete")
}

function layacopyDirFile(from, to) {
	var readDir = fs.readdirSync;
	var stat = fs.statSync;


	if (stat(from).isFile()) {
		mkdirsSyncLaya(to);
		fs.writeFileSync(to + path.sep + path.basename(from), fs.readFileSync(from));
		return
	}
	var copDir = function(src, dst) {
		var paths = fs.readdirSync(src);
		paths.forEach(function(pathLaya) {
			var _src = src + path.sep + pathLaya;
			var _dst = dst + path.sep + pathLaya;
			var isDir = stat(_src);
			if (isDir.isFile()) {
				if (path.extname(_src) == ".map") {} else {
					fs.writeFileSync(_dst, fs.readFileSync(_src));
				}

			} else {
				exists(_src, _dst, copDir);
			}
		})
	}

	function mkdirsSyncLaya(dirname, mode) {
		console.log(dirname);
		if (fs.existsSync(dirname)) {
			return true;
		} else {
			if (mkdirsSyncLaya(path.dirname(dirname), mode)) {
				fs.mkdirSync(dirname, mode);
				return true;
			}
		}
	}

	// 在复制目录前需要判断该目录是否存在，不存在需要先创建目录
	var exists = function(src, dst, callback) {
		mkdirsSyncLaya(dst);
		callback(src, dst);
	};
	// 复制目录
	exists(from, to, copDir);
}
